import { useEffect, useMemo, useState } from 'react'
import style from './index.module.less'
import PageComponent from '@components/pageComponent'
import { getDataRequest } from './ajax'
import { awaitWrap, formatDate, limitStr } from '@src/assets/js/tool'
import { Skeleton } from 'antd-mobile'
import PageEmpty from '@components/pageEmpty'
import { download } from '@js/downloadRename'
import EditContent from '@components/EditContent'
import { LinkOutline } from 'antd-mobile-icons'

async function initData (id, setData, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getDataRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setData(d)
  }
}

function Main ({ meta }) {
  const id = useMemo(() => {
    return typeof meta.id === 'string' && meta.id.length > 0 ? meta.id : ''
  }, [meta])
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(false)
  const file = useMemo(() => {
    return data && data.file instanceof Array ? data.file : []
  }, [data])
  useEffect(() => {
    if (id) {
      initData(id, setData, setLoading)
    }
  }, [id])
  return (
    <PageComponent title='文书详情'>
      <div className={style.container}>
        {
          loading && (
            <div className={style.loading}>
              <Skeleton.Title animated />
              <Skeleton.Paragraph animated />
            </div>
          )
        }
        {
          !loading && data === null && (
            <PageEmpty />
          )
        }
        {
          data && (
            <div className={style.article}>
              <h2 className={style.title}>{data.title}</h2>
              <div className={style['info-line']}>
                <span>{data.author}</span>
                <span>{formatDate(data.release_datetime, 'YYYY-MM-DD')}</span>
              </div>
              <EditContent value={data.content} />
              {
                file.length > 0 && (
                  <div className={style['download-list']}>
                    <div className={style['download-title']}>附件：</div>
                    <div className={style['download-content']}>
                      {file.map((li, i) => {
                        return (
                            <div className={style.download} key={i}>
                             <div className={style.icon}><LinkOutline /></div>
                              <a onClick={() => download(li.path, li.original_filename, li.filename)}>{limitStr(li.original_filename)}</a>
                            </div>
                        )
                      })}
                    </div>
                  </div>
                )
              }
            </div>
          )
        }
      </div>
    </PageComponent>
  )
}

export default Main
